﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace PrintApp
{
    public class TCPNetworkClient
    {
        private const int END_OF_TRANSMITION = 4;
        private IPEndPoint defaultServerEndPoint;

        public TCPNetworkClient(string address, int port)
        {
            this.defaultServerEndPoint = new IPEndPoint(IPAddress.Parse(address), port);
        }

        public string SendMessage(string message)
        {
            TcpClient client = new TcpClient();
            try
            {                
                client.Connect(defaultServerEndPoint);

                var writer = new BinaryWriter(new NetworkStream(client.Client), Encoding.UTF8);
                var reader = new BinaryReader(new NetworkStream(client.Client), Encoding.UTF8);

                byte[] buffer = Encoding.UTF8.GetBytes(message);
                writer.Write(buffer, 0, buffer.Length);
                writer.Write(END_OF_TRANSMITION);
                writer.Flush();
                writer.Close();

                var response = new StringBuilder();
                int c = -1;
                while ((c = reader.Read()) != END_OF_TRANSMITION)
                {
                    response.Append((char)c);
                }

                return response.ToString();
            }
            finally
            {
                client.Close();
            }
        }
    }
}
